package org.erepublik.company.thread;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;

import org.erepublik.company.Configuration;
import org.erepublik.company.CountryData;
import org.erepublik.company.scanner.CountryDataScanner;
import org.erepublik.company.service.JSONProductService;
import org.json.JSONArray;

public class CountryDataUpdater extends Thread {

    String urlToDatabaseDirectory;

    private final int SLEEP_TIME = 1000 * 60;
    private final long UPDATE_FREQUENCY; // 1 godzina
    String simpleName;
    private long previousScanTime;

    public CountryDataUpdater(long updateFreq) {

        UPDATE_FREQUENCY = updateFreq;
        this.simpleName = "country";
        urlToDatabaseDirectory = Configuration.databasePath + "/" + simpleName;
        previousScanTime = getLastScanTime(simpleName);
    }

    /**
     * @return zwraca czas ostatniego skanu (jest on zawarty w naziwe pliku
     *         przechowywujacego produkty)
     */
    public static long getLastScanTime(String simpleName) {

        String url = JSONProductService.getLastProductFile(simpleName);
        if (url == null)
            return 0;

        File file = new File(url);
        long timeStamp = getTimeStampFromFileName(file);
        return timeStamp;
    }

    public static long getTimeStampFromFileName(File file) {
        String[] fileName = file.getName().split("-");
        return Long.parseLong(fileName[0]);
    }

    public static long getTimeStampFromFileName(String file) {
        String[] fileName = file.split("-");
        return Long.parseLong(fileName[0]);
    }

    /**
     * Glowna petla skanera
     */
    public void run() {

        while (true) {
            try {
                Thread.sleep(SLEEP_TIME);
                long scanTime = new Date().getTime();
                System.out.println(simpleName + " updater...");
                long milisecondsSinceScan = scanTime - previousScanTime;
                System.out.print("ostatni skan był ");
                System.out.print(milisecondsSinceScan / (1000 * 60) + " min. ");
                System.out.print((milisecondsSinceScan % (1000 * 60)) / 1000 + " sec. temu ");
                if (milisecondsSinceScan > UPDATE_FREQUENCY) {

                    System.out.println("skanuje " + simpleName + "...");

                    CountryDataScanner scanner = new CountryDataScanner();
                    CountryData[] products = scanner.getMap().values().toArray(new CountryData[0]);

                    System.out.println("skonczylem skanowoac");
                    System.out.println("saving to file...");

                    File file = new File(urlToDatabaseDirectory + "/" + new Date().getTime() + "-" + simpleName + ".json");
                    file.createNewFile();
                    BufferedWriter out = new BufferedWriter(new FileWriter(file.getAbsolutePath()));
                    JSONArray jsonArray = new JSONArray();
                    for (int i = 0; i < products.length; i++) {
                        jsonArray.put(products[i].toJSONObject());
                    }
                    out.write(jsonArray.toString());
                    out.close();

                    previousScanTime = getLastScanTime(simpleName);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
